//
//  HistoryProblemListViewController.m
//  KIASupervisory
//
//  Created by tan_xin on 14-7-14.
//  Copyright (c) 2014年 MyCompany. All rights reserved.
//

#import "HistoryProblemListViewController.h"
#import "HistoryProblemDetailViewController.h"

@interface HistoryProblemListViewController ()

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableArray *problemList;

@end

@implementation HistoryProblemListViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
//    [self initHUD];
//    
//    self.networkManager = [[NetworkManager alloc] init];
    
    self.problemList = [[NSMutableArray alloc] init];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated {
    self.title = @"历史未完成问题";
    self.showLeftBtn = YES;
    self.showRightBtn = NO;
    [super viewWillAppear:animated];
    
//    self.navigationController.navigationBarHidden = NO;

    [self performSelector:@selector(getHistoryProblemList) withObject:nil afterDelay:0.3];
}

- (void)refreshViewByReloadData {
    [self getHistoryProblemList];
}

- (void)leftNavItemAction:(id)sender {
    AppDelegate *dele = [AppDelegate sharedDelegate];
    DDMenuController *menuVC = dele.ddLeftMenu;
    [menuVC showLeft:nil];
}

- (void)getHistoryProblemList {
//    if (!self.isRefreshing) {
//        self.isRefreshing = YES;
    
        [self.problemList removeAllObjects];
        
        UserInfo *user = [UserInfo instance];
        NSString *gonghao = [user.info objectForKeyOrNil:@"gh"];
        NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:
                               gonghao,@"gh", nil];
        [self.networkManager requestWithMethod:history parameter:param delegate:self];
        [self.HUD show:YES];
//    }
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - NetworkManagerDelegate
- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFinishedWithResult:(id)data {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    if ([data isKindOfClass:[NSDictionary class]]) {
        int code = [[data objectForKeyOrNil:@"code"] integerValue];
        if (code == 0) {
            [self.problemList removeAllObjects];
            
            if ([data count] > 0) {
                id dataObject = [data objectForKeyOrNil:@"data"];
                if ([dataObject isKindOfClass:[NSDictionary class]]) {
                    NSArray *problems = [dataObject objectForKeyOrNil:@"wtbs"];
                    if (![problems isKindOfClass:[NSNull class]] && [problems count] > 0) {
                        [self.problemList  addObjectsFromArray:problems];
                    }
                }
            }
            
            [self.tableView reloadData];
        } else {
            NSString *msg = [data objectForKeyOrNil:@"msg"];
            if ([msg  length] == 0) {
                msg = @"历史未完成问题获取失败，请稍后重试";
            }
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                            message:msg
                                                           delegate:nil
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}

- (void)network:(NetworkManager *)net methodId:(RequestMethodId)methodId didRequestFailedWithError:(NSError *)error {
    [self.HUD hide:YES];
    [self endRefresh];
    self.isRefreshing = NO;
    
    NSDictionary *errorInfo = error.userInfo;
    NSString *msg = [errorInfo objectForKeyOrNil:@"errorMsg"];
    
    NSInteger code = error.code;
    if (code != 1) {
        if ([msg length] == 0) {
            msg = @"历史未完成问题获取失败，请稍后重试";
        }
    }
    
    if ([msg length] > 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                        message:msg
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
}

- (void)clickTimeButton:(id)sender event:(id)event {
    NSSet *touches = [event allTouches];
    UITouch *touch = [touches anyObject];
    CGPoint currentTouchPosition = [touch locationInView:self.tableView];
    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:currentTouchPosition];
    if (indexPath == nil) {
        return;
    }
    
//    NSInteger row = indexPath.row;
    
    
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    [self endRefresh];
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//    return 5;
    return [self.problemList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"HistoryProblemCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
//        UIButton *btn = (UIButton *)[cell.contentView viewWithTag:103];
//        [btn addTarget:self action:@selector(clickTimeButton:event:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UILabel *label1 = (UILabel *)[cell.contentView viewWithTag:100];
    UILabel *label2 = (UILabel *)[cell.contentView viewWithTag:101];
    UILabel *label3 = (UILabel *)[cell.contentView viewWithTag:102];
    UIButton *btn = (UIButton *)[cell.contentView viewWithTag:103];
    
    NSInteger row = indexPath.row;
    
    if ([self.problemList count] > row) {
        NSDictionary *cellData = [self.problemList objectAtIndex:row];
        
        NSString *name = [cellData objectForKeyOrNil:@"jxsmc"]; //经销商名称
        NSString *code = [cellData objectForKeyOrNil:@"jxsdm"]; //经销商代码
        NSString *description = [cellData objectForKeyOrNil:@"wtms"]; //问题描述
        NSString *endtime = [cellData objectForKeyOrNil:@"sjz"]; //截止时间
        
        label1.text = name;
        label2.text = code;
        label3.text = description;
        
        if ([endtime isKindOfClass:[NSNull class]] || [endtime length] == 0) {
            endtime = @"截止时间";
        }
        [btn setTitle:endtime forState:UIControlStateNormal];
    }
    
    return cell;
    
}

#pragma mark - UITableViewDelegate methods
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60.0;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger row = indexPath.row;
    HistoryProblemDetailViewController *detailVC = (HistoryProblemDetailViewController *)[self.storyboard instantiateViewControllerWithIdentifier:@"HistoryProblemDetail"];
    if ([self.problemList count] > row) {
        NSDictionary *cellData = [self.problemList objectAtIndex:row];
        detailVC.problemInfo = cellData;
    }
    detailVC.showRightItem = YES;
    detailVC.canEditTime = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

@end
